<!DOCTYPE html>
<HTML>
<HEAD>
	<TITLE>目录配置</TITLE>
	<base href="${basePath}" />
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<link href="${mvcPath}/dacp-lib/bootstrap/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
	<link href="${mvcPath}/dacp-res/css/bootstrap-cover.css" type="text/css" rel="stylesheet" />
	<link href="${mvcPath}/dacp-lib/ztree/zTreeStyle.css" type="text/css" rel="stylesheet" />
    <link href="${mvcPath}/dacp-lib/fuelux/fuelux.min.css" type="text/css" rel="stylesheet" media="screen"/>
	<link href="${mvcPath}/dacp-view/aijs/css/ai.css" type="text/css" rel="stylesheet" />
	
	<script src="${mvcPath}/dacp-lib/jquery/jquery-1.10.2.min.js" type="text/javascript"></script>
	<script src="${mvcPath}/dacp-lib/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
	<script src="${mvcPath}/dacp-lib/jquery-plugins/jquery.layout-latest.js" type="text/javascript"></script>
	<script src="${mvcPath}/dacp-lib/ztree/jquery.ztree.all-3.5.min.js" type="text/javascript"></script>
	<script src="${mvcPath}/dacp-lib/jquery-plugins/jquery-contextMenu.js"></script>
	<script src="${mvcPath}/dacp-lib/jquery-plugins/jquery-artDialog.js"></script>
	<script src="${mvcPath}/dacp-lib/fuelux/fuelux.min.js"></script>
	<script type="text/javascript" src="${mvcPath}/dacp-lib/underscore/underscore-min.js"></script>
	
	<script src="${mvcPath}/dacp-lib/cryptojs/aes.js" type="text/javascript"></script>
	<script src="${mvcPath}/crypto/crypto-context.js" type="text/javascript"></script>
	<script src="${mvcPath}/dacp-view/aijs/js/ai.treeview.js"> </script>
	<script src="${mvcPath}/dacp-view/aijs/js/ai.core.js" type="text/javascript"></script>
	<script src="${mvcPath}/dacp-view/aijs/js/ai.jsonstore.js" type="text/javascript"></script>
	<script src="${mvcPath}/dacp-view/aijs/js/ai.field.js" type="text/javascript"></script>
	<script src="${mvcPath}/dacp-view/aijs/js/ai.grid.ux.js"></script>
	<script src="${mvcPath}/dacp-res/catalog/common/js/ai.meta.widget.js"></script>
	<script src="${mvcPath}/dacp-res/catalog/dataindex/js/jquery.ztree.exedit.js"></script>
</HEAD>
<style type="text/css">
	body {
		background-color: #f2f4f8;
	}
	html,body, .container-fluid,
	.row, .menu-list, .panel {
		height: 100%;
	}
	.menu-list>section {
		margin-bottom: 10px;
		overflow: auto;
		position: absolute;
		height: auto;
		bottom: 0;
		top: 0;
		right: 0;
		left: 15px;
	}
	#treeContainer {
		overflow:auto;
		padding:0px;
		margin-right:0px;
		border-right:0px;
	}
	.container-title {
		font-weight:bold;
		font-family:"微软雅黑";
		font-size:14px;
	}
	.detail-container {
		border:1px solid #ddd;
		border-top:0px;
	}
	.ztree li span.button.add {
		margin-left:2px;
		margin-right:-1px;
		background-position:-144px 0;
		vertical-align:top;
		*vertical-align:middle
	}
	.table-condensed > tbody > tr > td {
	    padding: 2px 5px;
	}
	.line {
		height:100%;
	}
	.fr {
	    float: right;
	}
	.fl {
	    float: left;
	}
	.menuright-search {
		display: inline-flex;
		height: 22px;
		margin-left: 30px;
	}
	.menuright-search>input{
		height: 22px;
		margin-right: 10px;
		border-radius: 0px;
	}
	.col-sm-9>input,
	.col-sm-9>textarea	{
		width:100%!important;
	}
<!-- -->
.repeater-header {
    min-height: 30px;
    padding-top: 3px;
    padding-bottom: 3px;
}
.repeater-viewport {
    height: 100%;
    width: 100%;
}
.repeater-canvas {
    height: 100%;
    padding-bottom: 80px;
    background-color:#fff;
    /* overflow: scroll; */
}
.repeater-thumbnail {
    border: 0px;
}
.dacptiles .icon {
    margin-top: 5px;
    margin-bottom: 10px;
    font-size: 32px;
}
.dacptiles .title {
    display: block;
    text-align: center;
    word-wrap: break-word;
    font-size: 12px;
}
#treeContainer {
	width:190px;
}
</style>

<script type="text/javascript">
var catalogCode = paramMap.catalogCode;
var catalogstore = ai.getStoreData("select * from data_catalog_def where CATALOG_CODE='"+catalogCode+"'");
var xmlid;
if(catalogstore.length>0){
	xmlid = catalogstore[0].XMLID;
}
Array.prototype.contains = function ( needle ) {
	  for (i in this) {
	    if (this[i] == needle) return true;
	  }
	  return false;
	}
var dbFrameItems = [
	{type:'text',label:'规则编号',fieldName:'RULECODE',notNull:'N',width:320},
	{type:'text',label:'上级编号',fieldName:'PARENTCODE',width:320},
	{type:'text',label:'名称',fieldName:'RULENAME',notNull:'N',width:320},
	{type:'combox',label:'节点类型',fieldName:'RULETYPE',notNull:'N',editable:'N',storesql:'TOPICCODE,节点|TOPICNAME,主题|LEVELNAME,层次',width:320},
	{type:'checkbox',label:'可包含对象',fieldName:'FUNC_ID',storesql:"select OBJTYPE,OBJNAME from METAOBJMODEL where PARENTCODE is not null and parentcode<>'META-OTHER' and parentcode<>'META' and STATE = 'Y' order by ORDSEQ asc ",width:320},
	//{type:'pick-grid',label:'可包含对象',fieldName:'FUNC_ID',storesql:'select objtype,objname from metaobjmodel where using_stat=\'Y\'',width:320}
	//,{type:'text',label:'命名约束类型',fieldName:'FUNC_NAME',width:320},
	{type:'text',label:'分类规则',fieldName:'RULEDEF',width:320}
	//{type:'text',label:'英文简称',fieldName:'RULELEVEL',width:320}
];
var editItems = [
	{type:'text',label:'名称',fieldName:'RULENAME',notNull:'N',width:320},
	{type:'text',label:'分类规则',fieldName:'RULEDEF',width:320}
];
var zTree;
var isCreate = true;
var orc;
var opc;
var orn;
var buildCatalogTree = function(sql){
	var ds_menu = new AI.JsonStore({
		sql: sql,
		key: "DBNAME,RULECODE",
		table: "METADB_STRUCT",
		pageSize: -1
	});
	//build menu tree ztree配置
	var setting = {
		view: {
			//addHoverDom: addHoverDom,
			//removeHoverDom: removeHoverDom,
			selectedMulti: false
		},
		data: {
			key: {
				name: "RULENAME"
			},
			simpleData: {
				enable: true,
				idKey: "RULECODE",
				pIdKey: "PARENTCODE",
				rootPId: ""
			}
		},
		callback: {
			onClick: onNodeClick,
		}
	}
	$.fn.zTree.init($("#treeContainer"), setting, ds_menu.root);
	zTree = $.fn.zTree.getZTreeObj("treeContainer");
	//点击ztree节点右边展示详情
	function onNodeClick(event, treeId, treeNode) {
		zTree.selectNode(treeNode);
		console.log(treeId);
		console.log(treeNode);
		var objstore =ai.getStoreData("select * from metadb_struct_obj where dbname = '"+catalogCode+"' and RULECODE like '"+treeNode.RULECODE+"%'");
		var xmlidstr;
		if(objstore.length>0){
			xmlidstr="'";
			for(var i=0;i<objstore.length;i++){
				xmlidstr+=objstore[i]["XMLID"]+"','";
			}
			xmlidstr = xmlidstr.substring(0,xmlidstr.length-2);
		}else{
			xmlidstr="''";
		}
		var sql = "select * from metaobj where XMLID IN ("+xmlidstr+")";
		console.log(sql);
		buildCatalogList(sql);
	}
	$("#addMenuInfo").click(function(){
		var callBack2 = function(){
			var rulecode = $("#RULECODE").val();
		   	var parentcode = $("#PARENTCODE").val();
		   	var rulename = $("#RULENAME").val();
			var ruletype = $("#RULETYPE").val();
			var ruledef = $("#RULEDEF").val();
			var func_id = "";
			var func_name="";
			var funcStore=new AI.JsonStore({
				sql:"select OBJTYPE,OBJNAME from METAOBJMODEL",
				table:"METAOBJMODEL",
				pageSize:-1
			});
			var str=document.getElementsByName("FUNC_ID");
			for(var i=0;i<str.length;i++){
				if(str[i].checked){
					func_id += str[i].value + ",";
					func_name += getFuncName(funcStore,str[i].value.trim()) + ",";
				}
			}
			func_id = func_id.substring(0,func_id.lastIndexOf(","));
			func_name = func_name.substring(0,func_name.lastIndexOf(","));
			var oldStructDataStoreSql = "select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNc_id,FUNC_NAME,RULEDEF,RULELEVEL,REMARK from metadb_struct where DBNAME='"+catalogCode+"'";
   			var oldStructDataStore = new AI.JsonStore({
   				sql:oldStructDataStoreSql,
                key:"RULECODE",
                pageSize:-1,
                table:"METADB_STRUCT"
   			});
   			var isExist = oldStructDataStore.getRecordByKey(rulecode);
	   		if(isExist){
	   			alert("当前规则编号已存在");
	   			return false;
	   		}
	   		var rec = ds_menu.getNewRecord();
			rec.set("XMLID",xmlid);
		   	rec.set("DBNAME",catalogCode);
		   	rec.set("RULECODE",rulecode);
		   	rec.set("PARENTCODE",parentcode);
		   	rec.set("RULENAME",rulename);
		   	rec.set("RULETYPE",ruletype);
		   	rec.set("FUNC_ID",func_id);
		   	rec.set("FUNC_NAME",func_name);
		   	rec.set("RULEDEF",ruledef);
		   	ds_menu.add(rec);
	   		var curnode = zTree.getSelectedNodes();
			zTree.addNodes(null, {
				RULENAME:rulename,
				RULECODE:rulecode,
			});
			ds_menu.commit();
		}
		ai.openFormDialog("新增主题规则",dbFrameItems,callBack2,null);
   	   	$("#PARENTCODE").val("");
   	   	$("#PARENTCODE").attr("readOnly","true");
   	 	$("#RULETYPE").val("TOPICCODE");
	});
	$("#AutoArchiving").click(function(){
		var obj = {};
		obj.catatype = 'busi'; 
		obj.setcode = catalogCode;
		$.ajax({ 
			type: "POST",
			// contentType: "application/json", 
			url:'${mvcPath}/catalog/autocatalog',
			async: false,
			data: obj,
			success:function(data) {
				var result = data.message;
				if(data.error) {
					result += ";  " + data.error;
				}
				alert(result);
			},
			error:function(data) {
				alert(JSON.stringify(data));
			}
   		});
		reBuildCatalogList();
	});
	$("#getMenu").click(function(){
		//'<div style="height:300px;" id="menuContainer"><div class="panel-heading" style="height:30px;width:100%;"><div class="btn-group" style="float:left;"><button class="btn btn-info btn-xs dropdown-toggle" data-toggle="dropdown">目录来源<span class="caret"></span></button><ul class="dropdown-menu"><li><a>数据库同步</a></li><li><a>标准目录同步</a></li></ul></div><div style="float:left;margin-left:300px;"><input type="checkbox" name="itemsalso">同时同步对象</div></div><div style="height:270px;width:100%;overflow:auto;" id="menuList"></div></div>',
		var dbStore = ai.getStoreData("select DBNAME,CNNAME from metadbcfg");
		var html = '<div style="height:300px;" id="menuContainer">'
		  		    +'<div class="panel-heading" style="height:30px;width:100%;padding-top:5px;">'
		  		     +'<div class="btn-group" style="float:left;">'
		  		      +'<button class="btn btn-info btn-xs dropdown-toggle" data-toggle="dropdown">目录来源'
		  		      +'<span class="caret"></span>'
		  		      +'</button>'
		  		      +'<ul class="dropdown-menu" id="menusource">'
		  		      +'<li><a href="javaScript:void(0)" title="STDCAT">标准目录</a></li>';
		for(var i=0;i<dbStore.length;i++){
			html += '<li><a href="javaScript:void(0)" title="'+dbStore[i].DBNAME+'">'+dbStore[i].CNNAME+'</a></li>'
		}
		html +=        '</ul>'
		  		     +'</div>'
		  		     +'<div style="float:left;margin-left:50px;">'
		  		      +'<input type="checkbox" name="itemsalso"><span class="btn btn-danger btn-xs" style="margin-top:-5px;">同时同步对象</span>'
		  		     +'</div>'
		  		    +'</div>'
		  		    +'<div style="height:270px;width:100%;overflow:auto;" id="menuList">'
		  		    +'</div>'
		  		   +'</div>';
		ai.loadWidget("dialog");
		art.dialog({
			title: '目录同步',
			width: 860,height:300,
			content: html,
			init: function () {
			},
			ok: function () {
				var selDataArray=seltreeGrid.getAllCheck();
				var ismenualso = document.getElementsByName("itemsalso")[0].checked;
				var structobjstore;
				if(ismenualso){
					structobjstore = new AI.JsonStore({
						sql:"select * from metadb_struct_obj where DBNAME='"+catalogCode+"'",
				        key:"DBNAME,XMLID",
				        pageSize:-1,
				        table:"METADB_STRUCT_OBJ"  
					});
				}
				var rulcodestore = ai.getStoreData("select RULECODE from metadb_struct where DBNAME='"+catalogCode+"'");
				var rulecodearr = [];
				for(var i=0;i<rulcodestore.length;i++){
					rulecodearr.push(rulcodestore[i].RULECODE);
				}
				if(selDataArray.length==0) {alert('你没有选择记录');return false;};
				for(var i=0;i<selDataArray.length;i++){
					if(rulecodearr.contains(selDataArray[i].RULECODE)){
						console.log("节点"+selDataArray[i].RULECODE+"已存在！添加失败！");
						continue;
					}
					var rec = ds_menu.getNewRecord();
					rec.set("XMLID",xmlid);
					rec.set("DBNAME",catalogCode);
					rec.set("RULECODE",selDataArray[i].RULECODE);
					rec.set("RULENAME",selDataArray[i].RULENAME);
					rec.set("PARENTCODE",selDataArray[i].PARENTCODE);
					rec.set("RULETYPE",selDataArray[i].RULETYPE);
					rec.set("FUNC_ID",selDataArray[i].FUNC_ID);
					rec.set("FUNC_NAME",selDataArray[i].FUNC_NAME);
					rec.set("RULEDEF",selDataArray[i].RULEDEF);
					ds_menu.add(rec);
					if(ismenualso){
						var itemstore = ai.getStoreData("select XMLID,OBJNAME from metaobj where DBNAME='"+selDataArray[i].DBNAME+"' and TOPICCODE='"+selDataArray[i].RULECODE+"'");
						if(itemstore.length>0){
							for(var j=0;j<itemstore.length;j++){
								var exist = structobjstore.getRecordByKey(catalogCode+","+itemstore[j].XMLID);
								if(exist){
									exist.set("RULECODE",selDataArray[i].RULECODE);
								}else{
									var newrec = structobjstore.getNewRecord();
									newrec.set("DBNAME",catalogCode);
									newrec.set("RULECODE",selDataArray[i].RULECODE);
									newrec.set("XMLID",itemstore[j].XMLID);
									newrec.set("OBJNAME",itemstore[j].OBJNAME);
									structobjstore.add(newrec);
								}
							}
						}
						structobjstore.commit();
					}
				}
				ds_menu.commit();
				ds_menu.select();
				$.fn.zTree.init($("#treeContainer"), setting, ds_menu.root);
				zTree = $.fn.zTree.getZTreeObj("treeContainer");
				reBuildCatalogList();
				},
			cancel:function(){
				}
		});
		var seltreeGrid;
		var selsql="select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_ID,FUNC_NAME,RULEDEF from metadb_struct where DBNAME='STDCAT'";
		function buildMenuTree(sql){
			var dbStrutStore=  new AI.JsonStore({
		        sql:sql,
		        key:"DBNAME,RULECODE",
		        pageSize:-1,
		        table:"METADB_STRUCT"  
			});
			var config = {
					id : "menuList",
					width : "800",
					renderTo : "menuList",
					headerAlign : "left",
					headerHeight : "30",
					dataAlign : "left",
					indentation : "8",
					hoverRowBackground : "true",
					folderColumnIndex : "0",
					showcheck:true,
					columns : [ 
						{headerText : "主题编号", dataField : "RULECODE", headerAlign : "center", width : "110" }, 
						{headerText : "主题名称", dataField : "RULENAME", headerAlign : "center", width : "125", dataAlign : "center", width : "100"},
						{headerText : "数据库名", dataField : "DBNAME", headerAlign : "center", width : "150", dataAlign : "center" }
					],
					keyfield : "RULECODE",
					pkeyfield : "PARENTCODE",
					titlefield : "RULENAME",
					iconfield : "",
					store:dbStrutStore,
					subtype : 'treegrid'
				};
			$("#menuList").empty();
			seltreeGrid = new TreeGrid(config);
		    seltreeGrid.show();
		}
		$("#menusource li").each(function(){
			$(this).click(function(){
				var db = $(this).find("a").attr("title");
				var sql = "select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_ID,FUNC_NAME,RULEDEF from metadb_struct where DBNAME='"+db+"'";
				buildMenuTree(sql);
			});
		});
			
		
		buildMenuTree(selsql);
	});
	function getFuncName(store,func_id){
		for(var i=0;i<store.getCount();i++){
			if(store.getAt(i).get("OBJTYPE").trim()==func_id){
				return store.getAt(i).get("OBJNAME");
			}else{
				continue;
			}
		}
		return "...";
	}
	var callBack1 = function(){
		var rulecode = $("#RULECODE").val();
	   	var parentcode = $("#PARENTCODE").val();
	   	var rulename = $("#RULENAME").val();
		var ruletype = $("#RULETYPE").val();
		var ruledef = $("#RULEDEF").val();
		var func_id = "";
		var func_name="";
		var funcStore=new AI.JsonStore({
			sql:"select OBJTYPE,OBJNAME from METAOBJMODEL",
			table:"METAOBJMODEL",
			pageSize:-1
		});
		var str=document.getElementsByName("FUNC_ID");
		for(var i=0;i<str.length;i++){
			if(str[i].checked){
				func_id += str[i].value + ",";
				func_name += getFuncName(funcStore,str[i].value.trim()) + ",";
			}
		}
		func_id = func_id.substring(0,func_id.lastIndexOf(","));
		func_name = func_name.substring(0,func_name.lastIndexOf(","));
	   	//先校验上级编号是否是存在
	   	if(parentcode){
	   		var isParent = ds_menu.getRecordByKey(catalogCode+","+parentcode);
	   		if(isParent || parentcode==""){
	   			
	   		}else{
	   			alert("父级编号不存在");
	   			return false;
	   		}
	   	}
	   	//再校验当前编号是否按照规则
	   	if(rulecode && rulename && ruletype){
	   		if(isCreate){
	   			var oldStructDataStoreSql = "select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNc_id,FUNC_NAME,RULEDEF,RULELEVEL,REMARK from metadb_struct where DBNAME='"+catalogCode+"'";
	   			var oldStructDataStore = new AI.JsonStore({
	   				sql:oldStructDataStoreSql,
	                key:"RULECODE",
	                pageSize:-1,
	                table:"METADB_STRUCT"
	   			});
	   			var isExist = oldStructDataStore.getRecordByKey(rulecode);
		   		if(isExist){
		   			alert("当前规则编号已存在!");
		   			return false;
		   		}
		   		var isnamexist = new AI.JsonStore({
					sql:"select * from metadb_struct where DBNAME='"+catalogCode+"' and PARENTCODE='"+parentcode+"' and RULENAME='"+rulename+"'",
					pageSize: -1
				});
				if(isnamexist.getCount()>0){
					alert("同一父节点下子节点不能同名!");
					return false;
				}
	   		}else{
	   			if(rulecode!=orc){
	   				var chkstore = new AI.JsonStore({
	   					sql:"select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_id,FUNC_NAME,RULEDEF,RULELEVEL,REMARK from metadb_struct where DBNAME='"+catalogCode+"' and RULECODE not like '"+orc+"%'",
	   					key:"RULECODE",
	   				    pageSize:-1,
	   				    table:"METADB_STRUCT"
	   				});
	   				var isexist = chkstore.getRecordByKey(rulecode);
	   				if(isexist){
	   					alert("当前规则编号已存在!");
	   		   			return false;
	   				}
	   			}
	   		}
	   		var _index = rulecode.lastIndexOf("_");
	   		var codePre = rulecode.substr(0,_index);
	   		var codeEnd = rulecode.substr(_index+1,rulecode.length);
	   		if(parentcode){
	   			if(codePre != parentcode){
	   				alert("编号需以父级编号为前缀!");
	   				return false;
	   			}
	   			if(!codeEnd){
	   				alert("编号需以父级编号加+\"_\"+编号值组成!");
	   				return false;
	   			}
	   		}else{
	   		}
	   	}else{
	   		alert("请填写带\" * \"的必填项!");
			return false;
	   	}
	   	if(isCreate){
	   		var rec = ds_menu.getNewRecord();
			rec.set("XMLID",xmlid);
		   	rec.set("DBNAME",catalogCode);
		   	rec.set("RULECODE",rulecode);
		   	rec.set("PARENTCODE",parentcode);
		   	rec.set("RULENAME",rulename);
		   	rec.set("RULETYPE",ruletype);
		   	rec.set("FUNC_ID",func_id);
		   	rec.set("FUNC_NAME",func_name);
		   	rec.set("RULEDEF",ruledef);
		   	ds_menu.add(rec);
	   		var curnode = zTree.getSelectedNodes();
			zTree.addNodes(curnode[0], {
				RULENAME:rulename,
				RULECODE:rulecode,
			});
			var newnode = zTree.getNodeByParam('RULECODE',rulecode);
			console.log(newnode);
	   	}else{
	   		if(parentcode!=opc||rulecode!=orc){
	   			ds_menu.select();
				var oldrecord = ds_menu.getRecordByKey(catalogCode+","+orc);
				ds_menu.remove(oldrecord);
				var oldnode = zTree.getNodeByParam('RULECODE',orc);
				zTree.removeNode(oldnode);
				var newrecord = ds_menu.getNewRecord();
				newrecord.set("XMLID",xmlid);
				newrecord.set("DBNAME",catalogCode);
				newrecord.set("RULECODE",rulecode);
				newrecord.set("PARENTCODE",parentcode);
				newrecord.set("RULENAME",rulename);
				newrecord.set("RULETYPE",ruletype);
				newrecord.set("FUNC_ID",func_id);
				newrecord.set("FUNC_NAME",func_name);
				newrecord.set("RULEDEF",ruledef);
				ds_menu.add(newrecord);
				var newpnode = zTree.getNodeByParam('RULECODE',parentcode);
				zTree.addNodes(newpnode,{
					RULENAME:rulename,
					RULECODE:rulecode,
				});
				var childstore = ai.getStoreData("select RULECODE,PARENTCODE from metadb_struct where DBNAME='"+catalogCode+"' and RULECODE like '"+orc+"%'");
		   		for(var i=0;i<childstore.length;i++){
		   			if(childstore[i].RULECODE==orc){
		   				
		   			}else{
		   				var oldrec = ds_menu.getRecordByKey(catalogCode+","+childstore[i].RULECODE);
		   				var oldnoden = zTree.getNodeByParam('RULECODE',childstore[i].RULECODE);
		   				zTree.removeNode(oldnoden);
		   				var newrec = ds_menu.getNewRecord();
		   	   			newrec.set("RULECODE",oldrec.get("RULECODE").replace(orc,rulecode));
		   	   			newrec.set("PARENTCODE",oldrec.get("PARENTCODE").replace(orc,rulecode));
		   	   			newrec.set("DBNAME",catalogCode);
		   	   			newrec.set("RULENAME",oldrec.get("RULENAME"));
		   	   			newrec.set("RULETYPE",oldrec.get("RULETYPE"));
		   	   			newrec.set("FUNC_ID",oldrec.get("FUNC_ID"));
		   	 			newrec.set("FUNC_NAME",oldrec.get("FUNC_NAME"));
		   	 			newrec.set("RULEDEF",oldrec.get("RULEDEF"));
		   	 			var newselfnode = zTree.getNodeByParam('RULECODE',rulecode);
			   	 		zTree.addNodes(newselfnode,{
							RULENAME:oldrec.get("RULENAME"),
							RULECODE:oldrec.get("RULECODE").replace(orc,rulecode),
						});
		   	 			ds_menu.remove(oldrec);
		   	 			ds_menu.add(newrec);
		   			}
		   		}
				
	   		}else{
	   			var oldnode = zTree.getNodeByParam('RULECODE',orc);
		   		oldnode.RULENAME = rulename;
	   			zTree.updateNode(oldnode);
	   			ds_menu.curRecord.set("FUNC_NAME",func_name);
	   		}
	   		
	   	}
	   	ds_menu.commit();
	   	ds_menu.select();
	   	//$.fn.zTree.init($("#treeContainer"), setting, ds_menu.root);
	}
	var callBack3 = function(){
		var rulename = $("#RULENAME").val();
		if(!rulename){
			alert("名称不能为空!");
			return false;
		}
		if(rulename!=orn){
			var isnamexist = new AI.JsonStore({
				sql:"select * from metadb_struct where DBNAME='"+catalogCode+"' and PARENTCODE='"+opc+"' and RULENAME='"+rulename+"'",
				pageSize: -1
			});
			if(isnamexist.getCount()>0){
				alert("同一父节点下子节点不能同名!");
				return false;
			}
			var oldnode = zTree.getNodeByParam('RULECODE',orc);
			oldnode.RULENAME = rulename;
			zTree.updateNode(oldnode);
		}
		ds_menu.commit();
	   	ds_menu.select();
	}
	$.contextMenu({
	    zIndex: 9999,
	    selector: ".curSelectedNode",
	    className: ".menufolder",
	    callback: function(key, options) {
	    	var curnode = zTree.getSelectedNodes()[0];
	    	function afterSelect(records){
	    		var idstore = ai.getStoreData("select XMLID from metadb_struct_obj where DBNAME='"+catalogCode+"'");
	    		var idarr = [];
	    		if(idstore.length>0){
	    			for(var i=0;i<idstore.length;i++){
	    				idarr.push(idstore[i].XMLID);
	    			}
	    		}
	    		for(var i=0;i<records.length;i++){
	    			if(!idarr.contains(records[i].get("KEYFIELD"))){
	    				ai.executeSQL("insert into metadb_struct_obj (DBNAME,RULECODE,XMLID,OBJNAME) values ('"+catalogCode+"','"+curnode.RULECODE+"','"+records[i].get("KEYFIELD")+"','"+records[i].get("VALUES1")+"')");
	    			}else{
	    				ai.executeSQL("update metadb_struct_obj set RULECODE='"+curnode.RULECODE+"' where DBNAME='"+catalogCode+"' and XMLID='"+records[i].get("KEYFIELD")+"'");
	    			}
	    		}
	    		var objstore =ai.getStoreData("select * from metadb_struct_obj where dbname = '"+catalogCode+"' and RULECODE like '"+curnode.RULECODE+"%'");
	    		var xmlidstr;
	    		if(objstore.length>0){
	    			xmlidstr="'";
	    			for(var i=0;i<objstore.length;i++){
	    				xmlidstr+=objstore[i]["XMLID"]+"','";
	    			}
	    			xmlidstr = xmlidstr.substring(0,xmlidstr.length-2);
	    		}else{
	    			xmlidstr="''";
	    		}
	    		var sql = "select * from metaobj where XMLID IN ("+xmlidstr+")";
	    		buildCatalogList(sql);
	    	}
	    	console.log(curnode);
	        if(key=="addnode"){
	        	isCreate = true;
	        	ai.openFormDialog("新增主题规则",dbFrameItems,callBack1,null);
	        	$("#RULECODE").val(curnode.RULECODE+"_");
	       	   	$("#PARENTCODE").val(curnode.RULECODE);
	       	   	$("#PARENTCODE").attr("readOnly","true");
	       	 	$("#RULETYPE").val("TOPICCODE");
	        }
	        if(key=="editnode"){
	        	isCreate = false;
	        	ds_menu.select();
	        	var rec = ds_menu.getRecordByKey(catalogCode+","+curnode.RULECODE);
	        	ds_menu.curRecord = rec;
	        	orc = rec.get("RULECODE");
	        	opc = rec.get("PARENTCODE");
	        	orn = rec.get("RULENAME");
	        	ai.openFormDialog("编辑当前节点",editItems,callBack3,ds_menu);
	        }
	        if(key=="deletenode"){
	        	var childstore = ai.getStoreData("select RULECODE from metadb_struct where DBNAME='"+catalogCode+"' and RULECODE like '"+curnode.RULECODE+"%'");
	        	if(childstore.length>1){
	        		var result1 = confirm("删除此节点的同时会删除其所有子节点及节点包含的对象!您确定要删除吗？");
	        		if(result1){
	        			var sql = "delete from metadb_struct_obj where DBNAME='"+catalogCode+"' and (";
	        			for(var i=0;i<childstore.length;i++){
	        				sql += ((i==0?"":" or ")+"RULECODE='"+childstore[i].RULECODE+"'");
	        				var rulecode = childstore[i].RULECODE;
	        				var record = ds_menu.getRecordByKey(catalogCode+","+rulecode);
	        				ds_menu.remove(record);
	        				var node = zTree.getNodeByParam('RULECODE',rulecode);
	        				zTree.removeNode(node);
	        			}
	        			sql += ")";
	        			ai.executeSQL(sql);
	        		}
	        	}else{
	        		var rec = ds_menu.getRecordByKey(catalogCode+","+curnode.RULECODE);
	        		var result = confirm("是否删除此节点及其包含的对象?");
	        		if(result){
	        			var sql = "delete from metadb_struct_obj where DBNAME='"+catalogCode+"' and RULECODE='"+curnode.RULECODE+"'";
	        			ds_menu.remove(rec);
	        			var node = zTree.getNodeByParam('RULECODE',curnode.RULECODE);
        				zTree.removeNode(node);
        				ai.executeSQL(sql);
	        		}
	        	}
	        	ds_menu.commit();
	        	reBuildCatalogList();
	        }
	        if(key=="clearnode"){
	        	var childstore = ai.getStoreData("select RULECODE from metadb_struct where DBNAME='"+catalogCode+"' and RULECODE like '"+curnode.RULECODE+"%' and RULECODE!='"+curnode.RULECODE+"'");
	        	if(childstore.length>0){
	        		var result1 = confirm("您确定要删除所有子节点码？");
	        		if(result1){
	        			var sql = "delete from metadb_struct_obj where DBNAME='"+catalogCode+"' and (";
	        			for(var i=0;i<childstore.length;i++){
	        				var rulecode = childstore[i].RULECODE;
	        				sql += ((i==0?"":" or ")+"RULECODE='"+childstore[i].RULECODE+"'");
	        				var record = ds_menu.getRecordByKey(catalogCode+","+rulecode);
	        				ds_menu.remove(record);
	        				var node = zTree.getNodeByParam('RULECODE',rulecode);
	        				zTree.removeNode(node);
	        			}
	        			sql += ")";
	        			ai.executeSQL(sql);
	        		}
	        	}else{
	        		alert("此节点没有子节点！");
	        		return;
	        	}
	        	ds_menu.commit();
	        	reBuildCatalogList();
	        }
	        if(key=="movenode"){
	        	//var node = zTree.getNodeByParam('RULECODE',"A_Z");
	        	//zTree.moveNode(node,curnode,"inner");
	        	//curnode.PARENTCODE=node.RULECODE;
	        	//curnode.RULECODE = node.RULECODE+"_"+curnode.RULECODE;
	        }
	        if(key=="chooseobj"){
	        	var existidstore = ai.getStoreData("select XMLID from metadb_struct_obj where dbname = '"+catalogCode+"' and RULECODE like '"+curnode.RULECODE+"%'");
	        	var existids;
	        	if(existidstore.length>0){
	        		existids = "'";
	        		for(var i=0;i<existidstore.length;i++){
	        			existids +=existidstore[i].XMLID+"','";
	        		}
	        		existids = existids.substring(0,existids.length-2);
	        	}else{
	        		existids = "''";
	        	}
	        	var addsql = "select XMLID keyfield,OBJNAME values1,OBJCNNAME values2,REMARK values3 FROM metaobj where XMLID not in ("+existids+")";
	        	var selBox = new SelectBox({sql:addsql,callback:afterSelect});
	        	selBox.show();
	        }
	    },
	    items: {
	        "addnode": {
	            name: '新增子节点',
	            className: "fav",
	            icon: "plus",
	            accesskey: "a",
	            
	        },
	        "editnode": {
	            name: '编辑节点',
	            className: "fav",
	            icon: "pencil",
	            accesskey: "e"
	        },

	        "sep1": "--------",
	        "deletenode": {
	            name: "删除节点",
	            className: "remove",
	            icon: "trash",
	            accesskey: "d"
	        },
	        "clearnode": {
	            name: "清空节点",
	            className: "fav",
	            icon: "trash",
	            accesskey: "c"
	        },
			"chooseobj":{
				name: "添加对象",
	            className: "fav",
	            icon: "plus",
	            accesskey: "b"
			}
			/*
	        "sep2": "--------",
	        "movenode": {
	            name: "移动节点",
	            className: "search",
	            icon: "search",
	            accesskey: "m"
	        },
	        "pickobjadd": {
	            name: "选择对象到此",
	            className: "search",
	            icon: "search",
	            accesskey: "p"
	        }
			*/
	    }
	});
	$("html").bind("click", function() {
	  $('.context-menu-list').filter(':visible').trigger('contextmenu:hide');
	});
}
var listView;
function reBuildCatalogList(sql){
	var objstore;
	if(sql){
		objstore = ai.getStoreData(sql);
	}else{
		objstore = ai.getStoreData("select * from metadb_struct_obj where dbname = '"+catalogCode+"'");
	}
	var xmlidstr;
	if(objstore.length>0){
		xmlidstr="'";
		for(var i=0;i<objstore.length;i++){
			xmlidstr+=objstore[i]["XMLID"]+"','";
		}
		xmlidstr = xmlidstr.substring(0,xmlidstr.length-2);
	}else{
		xmlidstr="''";
	}
	var sql = "select * from metaobj where XMLID IN ("+xmlidstr+")";
	listView.reload(sql);
}
var buildCatalogList = function(sql){
	var itemStore = new AI.JsonStore({
		sql: sql,
		pageSize: 20
	});
	listView = new AI.MetaList({});
	listView.showList({
		containerId: 'menu_detail',
		store: itemStore,
		objtype: 'META',
		title: "",
		//bodyHtml: '<div class="repeater-canvas col-md-12" style="padding-left:1px;padding-right:1px;height:100%;overflow:auto"></div> ',
		columns : [
	    	{header: "类型", dataIndex: "OBJTYPE", headerAlign: "center",width: "80",sortable:true,dimStore:new AI.JsonStore({sql:"SELECT objtype,objname FROM metaobjmodel group by objtype,objname",pageSize:-1})
	      ,render:function(rowData,colVal){
	        if(colVal=='folder') return '目录';
	        if(this.dimStore&&this.dimStore.getCount()>0){
	          var dim = _.find(this.dimStore.root,function(obj){
	            if(obj.OBJTYPE == colVal) return obj;
	          });
	          colVal = dim&&dim.OBJNAME?dim.OBJNAME:colVal;
	        }
	        return colVal;
	      }},
	      {header: "名称", dataIndex: "OBJNAME", headerAlign: "center",width: "180",sortable:true,maxLength:30},
	      {header: "中文名", dataIndex: "OBJCNNAME", headerAlign: "center", dataAlign: "center", width: "250",sortable:true,maxLength:30 },
	      {header: "业务分类",dataIndex:'TOPICCODE', headerAlign: "center", dataAlign: "center", width: "200" ,sortable:true,dimStore:new AI.JsonStore({sql:"select rulecode,rulename,parentcode from metadb_struct",pageSize:-1})
	        ,render:function(rowData,colVal){
	          var topicStore = this.dimStore;
	        	if(!colVal||colVal=='null') return '未知';
	        	var topicNames = [];
	        	function getTopicName(topicCode){
	        		var dim = _.find(topicStore.root,function(obj){
	            		if(obj.RULECODE == topicCode) return obj;
	          		});
	        		topicNames.push(dim&&dim.RULENAME?dim.RULENAME:topicCode);
	          		if(!_.isUndefined(dim)&&dim.PARENTCODE) getTopicName(dim.PARENTCODE);
	        	}
	        	if(topicStore&&topicStore.getCount()>0){
	        		getTopicName(colVal);
	          	}
	        	var result = "";
	        	for(i=topicNames.length-1;i>=0;i--){
	        		result +=((i==topicNames.length-1?'':'/')+topicNames[i]);
	        	} 
	        	return result||colVal;
	        }},
	      {header: "负责人",dataIndex:'CURDUTYER', headerAlign: "center", dataAlign: "center", width: "100" ,sortable:true},
	      //{header: "归属",dataIndex:'TEAM_CODE', headerAlign: "center", dataAlign: "center", width: "150" ,sortable:true}, 
	      {header: "状态",dataIndex:'STATE', headerAlign: "center", dataAlign: "center", width: "120" ,sortable:true,dimStore:new AI.JsonStore({sql:"SELECT rowcode,rowname FROM metaedimdef WHERE dimcode = 'DIM_STATE'",pageSize:-1})
	      ,render:function(rowData,colVal){
	        if(this.dimStore&&this.dimStore.getCount()>0){
	          var dim = _.find(this.dimStore.root,function(obj){
	            if(obj.ROWCODE == colVal) return obj;
	          });
	          colVal = dim&&dim.ROWNAME?dim.ROWNAME:colVal;
	        }
	        return colVal;
	      }},
	      {header: "备注",dataIndex:'REMARK', headerAlign: "center", dataAlign: "center", width: "250" ,sortable:true,maxLength:50}
	    ],
	    toolbarconfig:[
	      {type:'text',fieldLabel:'对象名称',width:120,name:'name',where:"(upper(OBJNAME) like upper('%{name}%') or upper(OBJCNNAME) like upper('%{name}%'))"},
	      {type:'combox',fieldLabel:'状态',width:210,name:'state',storesql:"select rowcode,rowname from metaedimdef where dimcode = 'DIM_STATE'",where:"state = '{state}'"},
	      {type:'button',fieldLabel:'查询',width:120,name:'query',actionId:'queryMetaObj'}
	    ]
	});
}
$(document).ready(function() {
	var sql1="select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_id,FUNC_NAME,RULEDEF,RULELEVEL,REMARK from metadb_struct where DBNAME='"+catalogCode+"'"; 
	buildCatalogTree(sql1);
	var objstore =ai.getStoreData("select * from metadb_struct_obj where dbname = '"+catalogCode+"'");
	var xmlidstr;
	if(objstore.length>0){
		xmlidstr="'";
		for(var i=0;i<objstore.length;i++){
			xmlidstr+=objstore[i]["XMLID"]+"','";
		}
		xmlidstr = xmlidstr.substring(0,xmlidstr.length-2);
	}else{
		xmlidstr="''";
	}
	var sql = "select * from metaobj where XMLID IN ("+xmlidstr+")";
	buildCatalogList(sql);
});
</script>

<BODY>
<div class="container-fluid">
	<div class="row">
		<div class="col-md-2 menu-list">
			<section class="panel panel-info">
				<header class="panel-heading">
					<span id="menuview" style="float: left">目录信息</span>
					<div class="btn-group" style="float: right">
						<button class="btn btn-primary btn-xs fr dropdown-toggle" data-toggle="dropdown">操作<span class="caret"></span></button>
						<ul class="dropdown-menu dropdown-menu-right">
						<li><a href="javaScript:void(0)" id="addMenuInfo">添加根目录</a></li>
						<li><a href="javaScript:void(0)" id="getMenu">目录同步</a></li>
						<li><a href="javaScript:void(0)" id="AutoArchiving">自动归档</a></li>
						</ul>
					</div>
				</header>
				<div class="ztree" id="treeContainer" style="padding: 10px;"></div>
			</section>
		</div>
		<div class="col-md-10">
			<section class="panel panel-info">
				<header class="panel-heading">
					<span class="hidden-sm">&nbsp;</span>
					<span id="menuinfo" style="float: left">对象信息</span>
				</header>
				<div class="panel-body" id="menu_detail" style="padding:10px"></div>
			</section>
		</div>
	</div>
</div>
</BODY>
</HTML>